import cv2
import os
import argparse

# 构造参数解析器并解析参数
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input", default='input', type=str, required=True,
                help="path to input image to resize")
ap.add_argument("-s", "--scale", default=0.5,type=float, required=False,
                help="scale to resize image")
ap.add_argument("-o", "--output", type=str, required=False,
                help="path to output image")
args = vars(ap.parse_args())
# 图片文件夹路径
input_folder = args["input"]
# 输出文件夹路径
output_folder = args["output"]
if output_folder is None or output_folder == '':
    output_folder = input_folder+os.sep+"resize"
# 缩放比例
scale = args["scale"]

# 确保输出文件夹存在
if not os.path.exists(output_folder):
    os.makedirs(output_folder)

# 获取输入文件夹中所有JPG图片文件
for filename in os.listdir(input_folder):
    if filename.endswith('.jpg') or filename.endswith('.JPG'):
        # 完整的文件路径
        file_path = os.path.join(input_folder, filename)
        # 读取图片
        image = cv2.imread(file_path)
        # 计算新的尺寸
        new_width = int(image.shape[1] * scale + 0.5)
        new_height = int(image.shape[0] * scale + 0.5)
        # 缩放图片
        resized_image = cv2.resize(image, (new_width, new_height), interpolation=cv2.INTER_AREA)
        # 写入缩放后的图片到输出文件夹
        output_file_path = os.path.join(output_folder, filename)
        cv2.imwrite(output_file_path, resized_image)
        print(f'Resized image: {filename}')